package com.example.commons.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class RedisUtil {

    @Autowired
    @Qualifier("jedisPool")
    private JedisPool jedisPool;

    public Jedis getJedis(int db) {
        Jedis jedis = jedisPool.getResource();
        jedis.select(db);
        return jedis;
    }

    public String get(int db, String key, boolean del) {
        try (Jedis jedis = this.getJedis(db)) {
            String val = jedis.get(key);
            if (del) {
                jedis.del(key);
            }
            return val;
        }
    }

    public void set(int db, String key, String val) {
        try (Jedis jedis = this.getJedis(db)) {
            jedis.set(key, val);
        }
    }

    public void setex(int db, String key, String val, long seconds) {
        try (Jedis jedis = this.getJedis(db)) {
            jedis.setex(key, seconds, val);
        }
    }

    public void del(int db, String... key) {
        try (Jedis jedis = this.getJedis(db)) {
            jedis.del(key);
        }
    }

}
